package com.tj.seed.common.interceptor;

import com.tj.seed.common.constant.ResultCode;
import com.tj.seed.common.context.UserContext;
import com.tj.seed.common.context.UserContextHolder;
import com.tj.seed.common.domain.Result;
import com.tj.seed.common.jwt.TokenParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
public class AuthInterceptor implements AsyncHandlerInterceptor {
    private final TokenParser tokenParser;

    public AuthInterceptor(TokenParser tokenParser) {
        Objects.requireNonNull(tokenParser);
        this.tokenParser = tokenParser;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (Objects.equals(HttpMethod.OPTIONS.name(), request.getMethod())) {
            return true;
        }
        String token = request.getHeader(UserContext.REQUEST_HEADER_AUTHORIZATION);
        if (!StringUtils.hasText(token)) {
            response.sendError(ResultCode.AUTH_NO_VALID_TOKEN.getCode(), "请登录");
            return false;
        }
        Result<UserContext> result = tokenParser.verify(token);
        if (!result.isSuccess()) {
            response.sendError(result.getCode(), result.getErrMsg());
            return false;
        }
        UserContextHolder.set(result.getData());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.remove();
    }
}
